$(document).ready(function(){

	$().submit=function(evt){
		var form = $(this);
		if(addUserForm.valid()==false){
			evt.preventDefault();
			bootbox.alert("请正确输入用户名和密码");
			return false;
		}

		var data=$("#inputForm").serialize();
		$.ajax({
	        url: form.attr("action"),
	        type: 'post',
	        data: data,
	        success:function(result){
	        	
	        	var reload = function(){
					window.location.reload();
	        	};
	        	bootbox.alert("修改成功",reload);
				return true;	        	
	        },
	        error: function(){bootbox.alert('修改失败');}
	      });
		evt.preventDefault();
		return false;

	}

	// 操作名验证
 	jQuery.validator.addMethod("isName", function(value, element) {
	        var name = /^[\u0391-\uFFE5\w]+$/;
	        return this.optional(element) || (name.test(value));
	    }, "不能输入特殊字符，请正确输入");
	//注册validate函数
	$("#addOperationForm").validate({
			event: "keyup" ,
			rules:{
				name:{
					required:true,
					maxlength:15,
					isName:true
				},
				
			},
			messages:{
				name:{
					required:"请输入操作名",
					maxlength:"操作名不能超过15个字符"
				},
				
			},
			rules:{
				code:{
					required:true,
					maxlength:15,
					isName:true
				},
				
			},
			messages:{
				code:{
					required:"请输入操作标识",
					maxlength:"操作标识不能超过15个字符"
				},
				
			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});
	$("#editOperationForm").validate({
			event: "keyup" ,
			rules:{
				name:{
					required:true,
					maxlength:15,
					isName:true
				},
				
			},
			messages:{
				name:{
					required:"请输入操作名",
					maxlength:"操作名不能超过15个字符"
				},
				
			},rules:{
				code:{
					required:true,
					maxlength:15,
					isName:true
				},
				
			},
			messages:{
				code:{
					required:"请输入操作标识",
					maxlength:"操作标识不能超过15个字符"
				},
				
			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});
});


	/* 获取多选框项id */
	function getIds(){
		var checkIds = [];
		// bootbox.alert($("#userList input[type='checkbox']").length)
		$("#operationListBody input[type='checkbox']").each(function(index){
			if($(this).is(':checked')){
				var id = $(this).val();
				checkIds.push(id);
			}
		});
		
		return checkIds;
	}


	function deleteOperations(){
		var ids = getIds();
				if(ids.length==0){
					bootbox.alert("请至少选择一项");
					return;
				}
		bootbox.confirm("是否要删除操作？",function(result){
			if(result){

				var data = [{ name: 'ids', value: ids }];
				$.ajax({
			        url: "delete",
			        type: 'post',
			        data: data,
			        success:function(returnVal){
			        	
			        	var reload = function(){
							var url = window.location.href;
//							if( url.split("?").length>1){
//								//不在第一页， 跳转回第一页。。。⊙﹏⊙b汗
//								url = url.substr(0,url.length-1)+ "1";;
//								window.location.href = url;	
//				        	}
							if(url.indexOf("page=") > 0){
								url = url.replace("page=","old_pa=");
								url += "&page=1";
								window.location.href = url;
							}else{
								window.location.reload();
							}
			        	};
                        if(returnVal.error != null){
                            bootbox.alert("删除失败,请确认该操作没有授权任何角色",reload);
                            return;
                        }
			        	bootbox.alert("删除成功",reload);
			        	// window.location.reload();
			        	
			        },
			        error: function(){bootbox.alert('删除失败');}
			      });
			}else{
				return;
			}
		});
		
	}

	function addOperation(){

		var operationName = $('#input-operation-name').val();
		var operationCode = $('#input-operation-code').val();
		var form = $('#addOperationForm');
		if(form.valid()==false){			
			// bootbox.alert("请正确输入操作名");
			return false;
		}	
		// if(operationName=="")
		// {
		// 	bootbox.alert("请正确输入操作名");
		// 	return;
		// }
		var data = [{ name: 'operationName', value:  operationName},
		            { name: 'operationCode', value:  operationCode}];		
		$.ajax({
	        url: "add",
	        type: 'post',
	        data: data,
	        success:function(result){
	        	
	        	if(result=="success"){

		        	bootbox.alert("创建成功",function(){
	        		window.location.reload();
	        	});			
	        	}else if(result=="same"){
	        		bootbox.alert("已存在相同名字的操作");
	        	}else{
	        		bootbox.alert("创建失败");
	        	}

	        	
	        },
	        error: function(){bootbox.alert(result);}
	      });
	}

//
function editOperation(opID) {
	//编辑操作中文名输入框
	var ed_operation_name = $('#ed-operation-name');
	var ed_operation_code= $('#ed-operation-code');
	var ed_operation_id = $('#ed-operation-id');

	// ajax请求
	var data = [ {name : 'id',value : opID} ];
	$.ajax({
		url : "get",
		type : 'post',
		data : data,
		dataType : "json",
		success : function(result) {
			console.log(result);
			ed_operation_name.val(result.name);
			ed_operation_code.val(result.code)
			ed_operation_id.val(result.id);

			// 打开窗口时
			$('#editOperationModal').modal("show");
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});

}


function checkAndSubmit(formId,inputId){
      
    var form = $("#"+formId); 
	if(!(form.valid()) ) {
		return false;
	}
     
      var operationName = $("#"+inputId).val();
        var url = "isExist?name="+operationName;
        //验证该操作名是否存在
        $.ajax({
            url : url,
            type : 'GET',
            dataType : "json",
            success : function(result) {
                console.log(result);
                if(result.error){
                    bootbox.alert(result.error);
                }else {
                  	// $("#"+formId).submit());
                  	//ajax提交修改的操作
                  	$.ajax({
		                cache: true,
		                type: "POST",
		                url: form.attr("action"),
		                data: form.serialize(),// 你的formid
		                async: false,
		                error: function(request) {
		                    // alert("Connection error");
		                    bootbox.alert("提交失败");
		                },
		                success: function(data) {
		                	
		                    $("#editOperationModal").modal("hide");
		                    bootbox.alert("更新用户信息成功",function(){
		                    	window.location.reload();	
		                    });
		                }
		            });
                }
            },
            error : function(e,error,xhr) {
                bootbox.alert("服务器繁忙，请稍后再试！");
                return;
            }
        });
}

function selectAll(id,parent){
	var selectAllCheckbox = $("#"+id);
	var checkList = $("#"+parent+" input[type='checkbox']");
	if(selectAllCheckbox.is(':checked')){
		checkList.each(function(index) {
			this.checked = true;
		});
	}else{
		checkList.each(function(index) {
			this.checked = false;
		});
	}
}